<template>
  <div class="container">
    <van-nav-bar
      title="搜索中心"
      left-arrow
      @click-left="$router.back()"
    />
    <van-search
      shape="round"
      v-model.trim="keyWord"
      @search="onSearch"
      placeholder="请输入搜索关键词"
    />
    <!-- 联想搜索 -->
    <van-cell-group
      class="suggest-box"
      v-if="keyWord"
    >
      <van-cell
        icon="search"
        :key="sug"
        v-for="sug in suggestList"
      >
        <p
          v-html="sug"
          @click="onSearch(sug.replace(`<span>${keyWord}</span>`,keyWord))"
        >
          <!-- <span>j</span>ava -->
        </p>
      </van-cell>
    </van-cell-group>
    <!-- 历史记录 -->
    <div
      class="history-box"
      v-else-if="historyList.length"
    >
      <div class="head">
        <span>历史记录</span>
        <van-icon
          @click="clearHistory"
          name="delete"
        ></van-icon>
      </div>
      <van-cell-group>
        <van-cell
          :key="item"
          v-for="item in historyList"
        >
          <a
            @click="toSearch(item)"
            class="word_btn"
          >{{item}}</a>
          <van-icon
            @click="delHistory(item)"
            class="close_btn"
            slot="right-icon"
            name="cross"
          />
        </van-cell>
      </van-cell-group>
    </div>
  </div>
</template>

<script>
import { suggest } from '@/api/article'
const TT_SEARCH_HISTORY = 'TT_SEARCH_HISTORY'
export default {
  name: 'search-index',
  data () {
    return {
      // 搜索关键词
      keyWord: '',
      // 联想词数据
      suggestList: [],
      // 搜索历史
      historyList: JSON.parse(localStorage.getItem(TT_SEARCH_HISTORY)) || []
    }
  },
  watch: {
    keyWord () {
      // 清除定时器异步任务
      this.timer && clearTimeout(this.timer)
      // 函数防抖：当用户停止输入后600ms后处理联想词；
      // 如果600ms内再次输入内容，会清除上一次的任务，重新计时
      // 缓存定时器=>this.timer
      this.timer = setTimeout(async () => {
        if (!this.keyWord) {
          // 为空 =>删除联想词结果
          this.suggestList = []
          return
        }
        const { status, data } = await suggest(this.keyWord)
        if (status === 200) {
          this.suggestList = data.options.map((item) => item.toLowerCase().replace(this.keyWord, `<span>${this.keyWord}</span>`))
          console.log(this.suggestList)
        }
      }, 600)
    }
  },
  methods: {
    // 搜索
    onSearch (val) {
      console.log(1, val)
      if (!val) return
      // 处理搜索历史
      const keySet = new Set(this.historyList)
      keySet.add(val)
      this.historyList = [...keySet]
      //  更新本地缓存
      localStorage.setItem(TT_SEARCH_HISTORY, JSON.stringify(this.historyList))
      // 跳转搜索结果
      this.$router.push({ path: '/search/result', query: { keyWord: val } })
    },
    // 从搜索历史到结果页
    toSearch (key) {
      this.$router.push({ path: '/search/result', query: { keyWord: key } })
    },
    // 删除搜索历史
    delHistory (key) {
      const i = this.historyList.findIndex((item) => item === key)
      this.historyList.splice(i, 1)
      localStorage.setItem(TT_SEARCH_HISTORY, JSON.stringify(this.historyList))
    },
    // 清空搜搜历史
    clearHistory () {
      this.historyList = []
      localStorage.setItem(TT_SEARCH_HISTORY, null)
    }
  }
}
</script>

<style scoped lang='less'>
.suggest-box {
  /deep/ .van-cell {
    padding: 10px 20px;
    color: #999;
    p {
      span {
        color: red;
      }
    }
  }
}
.history-box {
  padding: 0 20px;
  .head {
    line-height: 36px;
    color: #999;
    .van-icon {
      font-size: 16px;
      float: right;
      margin-top: 10px;
    }
  }
  .van-cell {
    padding: 10px 0;
  }
  .word_btn {
    color: #3296fa;
  }
  .close_btn {
    margin-top: 5px;
    color: #999;
  }
}
</style>
